#ifndef __UTILS_H__
#define __UTILS_H__

#include <pthread.h>


#define THREAD_SIGNAL SIGUSR1

#define OK          0
#define FAILED      -1

typedef struct condition_val
{
    pthread_mutex_t mutex;
    pthread_cond_t cond_data_available;
    void *val;
    unsigned int waittick;
    int released;
} condition_val_ts;


typedef enum utils_status
{
    EN_UTILS_OK,
    EN_UTILS_ERR_FAILED,
    EN_UTILS_ERR_TIMEOUT,
    EN_UTILS_ERR_NOMEM,
} utils_status_te;

typedef enum thread_detach_state
{
    EN_THREAD_JOINABLE,
    EN_THREAD_DETACHED
} thread_detach_state_te;

typedef enum thread_state
{
    EN_THREAD_STOPPED,   /**< 线程停止 */
    EN_THREAD_RUNNING,   /**< 线程运行 */
    EN_THREAD_STOPPING,  /**< 线程将停止 */
} thread_state_te;

typedef void *(*threadfunc)(void *);

typedef struct utils_thread
{
    pthread_mutex_t mtx;
    volatile thread_state_te running_state;     /**< 线程状态 */
    thread_detach_state_te detach_state;        /**< 线程是分离还是joinable */
    pthread_t tid;
    threadfunc tfunc;
} utils_thread_ts;

extern utils_status_te utils_thread_start(threadfunc prThreadFunction, utils_thread_ts *psThreadInfo);

extern utils_status_te utils_thread_stop(utils_thread_ts *psThreadInfo);

extern int utils_check_running(utils_thread_ts *psThreadInfo);

extern utils_status_te utils_cond_init(condition_val_ts *pcond);

extern utils_status_te utils_cond_destroy(condition_val_ts *pcond);

extern utils_status_te utils_cond_timedwait(condition_val_ts *pcond, unsigned int u32WaitTimeout);

extern utils_status_te utils_cond_signal(condition_val_ts *pcond, void *newval);

extern utils_status_te utils_cond_broadcast(condition_val_ts *pcond, void *newval);

extern utils_status_te utils_cond_wait_until(condition_val_ts *cond, unsigned int millisecond);

extern utils_status_te utils_mem_dup(void **dst, void *src, unsigned int size);

extern char *utils_fileread(char *path, char *buf, size_t *length);

extern int utils_filewrite(char *path, char *buf, size_t length);

extern unsigned long long ntohll(unsigned long long host);

extern unsigned long long htonll(unsigned long long host);

extern int base64_encode(const void *in, int len, char *out);

extern int base64_decode(const char *in, int len, void *out);


#endif